<template>
  <div class="main-layout">
    <n-layout has-sider>
      <n-layout-sider bordered collapse-mode="width" :collapsed-width="64" :width="240" :collapsed="collapsed"
        show-trigger @collapse="collapsed = true" @expand="collapsed = false" class="layout-sider">
        <div class="logo-container">
          <img src="../assets/logo.svg" alt="皮影快闪" class="logo" />
          <h1 class="app-name" v-if="!collapsed">皮影快闪</h1>
        </div>

        <n-menu :collapsed="collapsed" :collapsed-width="64" :collapsed-icon-size="22" :options="menuOptions"
          :value="activeKey" @update:value="handleMenuUpdate" />

        <div class="sider-footer" :class="{ collapsed }">
          <n-tooltip placement="right" trigger="hover" v-if="collapsed">
            <template #trigger>
              <n-button quaternary circle @click="navigateTo('/user/profile')">
                <template #icon><n-icon>
                    <PersonOutline />
                  </n-icon></template>
              </n-button>
            </template>
            {{ username }}
          </n-tooltip>

          <n-dropdown v-else trigger="click" :options="userMenuOptions" @select="handleUserAction">
            <div class="user-info">
              <n-avatar round size="small" :src="userAvatar" :fallback-src="defaultAvatar" />
              <span class="username">{{ username }}</span>
              <n-icon>
                <ChevronDownOutline />
              </n-icon>
            </div>
          </n-dropdown>
        </div>
      </n-layout-sider>

      <n-layout>
        <!-- layout-header 已完全隐藏，内容移至抽屉侧边栏 -->

        <n-layout-content class="layout-content">
          <router-view v-slot="{ Component }">
            <transition name="fade" mode="out-in">
              <component :is="Component" />
            </transition>
          </router-view>
        </n-layout-content>
      </n-layout>
    </n-layout>

    <n-drawer v-model:show="showNotificationDrawer" placement="right" :width="340" :trap-focus="false"
      display-directive="show">
      <n-drawer-content title="通知中心">
        <template #header>
          <div class="drawer-header">
            <div class="header-title">通知中心</div>
            <div class="header-actions">
              <n-button text @click="markAllAsRead">
                全部已读
              </n-button>
              <n-button text @click="goToSettings">
                <template #icon><n-icon>
                    <SettingsOutline />
                  </n-icon></template>
              </n-button>
            </div>
          </div>
        </template>

        <div class="notifications-container">
          <n-tabs type="segment" animated>
            <n-tab-pane name="all" tab="全部">
              <n-scrollbar style="max-height: calc(100vh - 140px)" :x-scrollable="false">
                <n-empty v-if="notifications.length === 0" description="暂无通知" />
                <n-list v-else>
                  <n-list-item v-for="notification in notifications" :key="notification.id">
                    <n-thing :title="notification.title" :description="notification.time">
                      <template #avatar>
                        <n-avatar round :src="notification.avatar" :style="{ backgroundColor: notification.color }">
                          {{ notification.avatar ? '' : notification.title.charAt(0) }}
                        </n-avatar>
                      </template>
                      <template #default>
                        <p>{{ notification.content }}</p>
                      </template>
                      <template #footer>
                        <n-space>
                          <n-button text size="small" @click="viewNotification(notification)">
                            查看
                          </n-button>
                          <n-button text size="small" @click="removeNotification(notification)">
                            删除
                          </n-button>
                        </n-space>
                      </template>
                    </n-thing>
                  </n-list-item>
                </n-list>
              </n-scrollbar>
            </n-tab-pane>
            <n-tab-pane name="unread" tab="未读">
              <n-empty description="暂无未读通知" />
            </n-tab-pane>
            <n-tab-pane name="important" tab="重要">
              <n-empty description="暂无重要通知" />
            </n-tab-pane>
          </n-tabs>
        </div>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, h } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  NLayout,
  NLayoutSider,
  NLayoutHeader,
  NLayoutContent,
  NMenu,
  NBreadcrumb,
  NBreadcrumbItem,
  NButton,
  NButtonGroup,
  NAvatar,
  NBadge,
  NIcon,
  NTooltip,
  NDropdown,
  NDrawer,
  NDrawerContent,
  NTabs,
  NTabPane,
  NEmpty,
  NList,
  NListItem,
  NThing,
  NSpace,
  NScrollbar
} from 'naive-ui'
import {
  HomeOutline,
  FileTrayFullOutline,
  ImagesOutline,
  PricetagsOutline,
  LayersOutline,
  PersonOutline,
  SettingsOutline,
  NotificationsOutline,
  HelpCircleOutline,
  LogOutOutline,
  MoonOutline,
  SunnyOutline,
  ChevronDownOutline,
  SaveOutline,
  ShareOutline
} from '@vicons/ionicons5'
import { useAppStore } from '../stores/appStore'
import { useUserStore } from '../stores/userStore'
import { storeToRefs } from 'pinia'

const router = useRouter()
const route = useRoute()
const appStore = useAppStore()
const userStore = useUserStore()

// 从store获取状态
const { themeMode, notifications } = storeToRefs(appStore)
const { currentUser } = storeToRefs(userStore)

// 侧边栏状态
const collapsed = ref(false)

// 通知抽屉状态
const showNotificationDrawer = ref(false)

// 活跃菜单项
const activeKey = computed(() => {
  const path = route.path
  if (path.startsWith('/workspace')) return 'workspace'
  if (path.startsWith('/projects')) return 'projects'
  if (path.startsWith('/assets')) return 'assets'
  if (path.startsWith('/templates')) return 'templates'
  return 'home'
})

// 菜单配置
const menuOptions = [
  {
    label: '首页',
    key: 'home',
    icon: renderIcon(HomeOutline),
    path: '/'
  },
  {
    label: '我的项目',
    key: 'projects',
    icon: renderIcon(FileTrayFullOutline),
    path: '/projects'
  },
  {
    label: '工作区',
    key: 'workspace',
    icon: renderIcon(LayersOutline),
    path: '/workspace/editor'
  },
  {
    label: '素材库',
    key: 'assets',
    icon: renderIcon(ImagesOutline),
    path: '/assets'
  },
  {
    label: '模板',
    key: 'templates',
    icon: renderIcon(PricetagsOutline),
    path: '/templates'
  }
]

// 用户菜单配置
const userMenuOptions = [
  {
    label: '个人中心',
    key: 'profile',
    icon: renderIcon(PersonOutline)
  },
  {
    label: '设置',
    key: 'settings',
    icon: renderIcon(SettingsOutline)
  },
  {
    type: 'divider',
    key: 'd1'
  },
  {
    label: '退出登录',
    key: 'logout',
    icon: renderIcon(LogOutOutline)
  }
]

// 面包屑配置
const breadcrumbItems = computed(() => {
  const path = route.path
  const items = [
    { title: '首页', path: '/' }
  ]

  if (path.includes('/projects')) {
    items.push({ title: '我的项目', path: '/projects' })
  }

  if (path.includes('/workspace')) {
    items.push({ title: '工作区', path: '/workspace/editor' })

    if (path.includes('/settings')) {
      items.push({ title: '项目设置', path: '/workspace/settings' })
    }
  }

  return items
})

// 用户信息
const username = computed(() => {
  return currentUser.value?.username || '未登录'
})

const userAvatar = computed(() => {
  return currentUser.value?.avatar || ''
})

// 默认头像
const defaultAvatar = 'https://placeholder.pics/svg/40/DEDEDE/555555/用户'

// 未读通知数量
const unreadCount = computed(() => {
  return notifications.value.filter(n => !n.read).length
})

// 判断是否为暗色模式
const isDarkMode = computed(() => {
  return themeMode.value === 'dark'
})

// 是否显示工具栏
const showToolbar = computed(() => {
  return route.path.includes('/workspace')
})

// 渲染图标
function renderIcon(icon: any) {
  return () => h(NIcon, null, { default: () => h(icon) })
}

// 处理菜单项点击
const handleMenuUpdate = (key: string) => {
  const item = menuOptions.find(item => item.key === key)
  if (item && item.path) {
    router.push(item.path)
  }
}

// 导航到指定路径
const navigateTo = (path: string) => {
  router.push(path)
}

// 处理用户菜单操作
const handleUserAction = (key: string) => {
  switch (key) {
    case 'profile':
      router.push('/user/profile')
      break
    case 'settings':
      router.push('/user/settings')
      break
    case 'logout':
      userStore.logout()
      router.push('/account/login')
      break
  }
}

// 切换深色/浅色模式
const toggleTheme = () => {
  appStore.toggleTheme()
}

// 打开通知抽屉
const openNotifications = () => {
  showNotificationDrawer.value = true
}

// 打开帮助
const openHelp = () => {
  window.open('https://help.example.com', '_blank')
}

// 标记所有通知为已读
const markAllAsRead = () => {
  notifications.value.forEach(notification => {
    notification.read = true
  })
}

// 查看通知
const viewNotification = (notification: any) => {
  notification.read = true
  // 根据通知类型执行不同操作
  console.log('查看通知', notification)
}

// 删除通知
const removeNotification = (notification: any) => {
  const index = notifications.value.findIndex(n => n.id === notification.id)
  if (index !== -1) {
    notifications.value.splice(index, 1)
  }
}

// 前往设置
const goToSettings = () => {
  router.push('/user/settings')
}
</script>

<style lang="scss" scoped>
.main-layout {
  height: 100vh;

  .layout-sider {
    border-right: 1px solid var(--border-color);
    display: flex;
    flex-direction: column;

    .logo-container {
      display: flex;
      align-items: center;
      padding: 16px;

      .logo {
        width: 32px;
        height: 32px;
      }

      .app-name {
        margin-left: 12px;
        font-size: 16px;
        font-weight: 600;
        white-space: nowrap;
      }
    }

    .sider-footer {
      margin-top: auto;
      padding: 16px;
      border-top: 1px solid var(--border-color);

      &.collapsed {
        display: flex;
        justify-content: center;
        padding: 16px 0;
      }

      .user-info {
        display: flex;
        align-items: center;
        cursor: pointer;
        padding: 4px 8px;
        border-radius: 4px;

        &:hover {
          background-color: var(--item-color-hover);
        }

        .username {
          margin: 0 8px;
          flex: 1;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }

  .layout-header {
    height: 56px;
    padding: 0 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .header-left,
    .header-center,
    .header-right {
      display: flex;
      align-items: center;
    }

    .header-left {
      min-width: 200px;
    }

    .header-center {
      flex: 1;
      justify-content: center;
    }

    .header-right {
      gap: 8px;
    }
  }

  .layout-content {
    padding: 0;
    overflow-y: auto;
  }

  .drawer-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-right: 8px;

    .header-title {
      font-size: 16px;
      font-weight: 600;
    }

    .header-actions {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }

  .fade-enter-active,
  .fade-leave-active {
    transition: opacity 0.2s ease;
  }

  .fade-enter-from,
  .fade-leave-to {
    opacity: 0;
  }
}
</style>